import { useEffect, useState } from 'react'
import axios from 'axios'
import { notification } from 'antd'

function usePublish(type) {
  const [dataSource, setDataSource] = useState([])
  const { username } = JSON.parse(localStorage.getItem("token"))
  useEffect(() => {
    axios.get(`http://localhost:5000/news?author=${username}&publishState=${type}&_expand=category`)
      .then(res => {
        console.log(res.data);
        setDataSource(res.data)
      })
  }, [username, type])

  const handlePublish = (id) => {
    // console.log(id);
    setDataSource(dataSource.filter(item => item.id !== id))

    axios.patch(`http://localhost:5000/news/${id}`, {
      "publishState": 2
    }).then(res => {
      notification.info({
        title: "通知",
        description: "【发布管理/已经发布】中查看新闻",
        placement: "bottomRight"
      })
    })

  }

  const handleSunset = (id) => {
    setDataSource(dataSource.filter(item => item.id !== id))

    axios.patch(`http://localhost:5000/news/${id}`, {
      "publishState": 3
    }).then(res => {
      notification.info({
        title: "通知",
        description: "【发布管理/已下线】中查看新闻",
        placement: "bottomRight"
      })
    })

  }

  const handleDelete = (id) => {
    setDataSource(dataSource.filter(item => item.id !== id))

    axios.delete(`http://localhost:5000/news/${id}`).then(res => {
      notification.info({
        title: "通知",
        description: "已删除新闻",
        placement: "bottomRight"
      })
    })

  }

  return {
    dataSource,
    handlePublish,
    handleDelete,
    handleSunset
  }
}

export default usePublish